import router from '@/router'
export const WebsocketMixin = {
  data() {
    return {
      websock: null,
      socketUrl: '/Iotwebsocket/{1}',
      count: 0,
      websocketMessage: {}
    }
  },
  mounted() {
    this.initWebSocket();
  },
  destroyed() {
    // 离开页面生命周期函数
    this.websock.close()
  },
  deactivated() {
    // 离开页面生命周期函数
    this.websock.close()
  },
  methods: {
    initWebSocket: function () {
      if (this.websock) {
        this.websock.close()
      }
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var path = window.location.origin
      // var path = 'http://zhyq.xazhsq.cn/'
      var url = path.replace("https://", "wss://").replace("http://", "ws://") + process.env.VUE_APP_BASE_API + this.socketUrl;
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketOnopen;
      this.websock.onerror = this.websocketOnerror;
      this.websock.onmessage = this.websocketOnmessage;
      this.websock.onclose = this.websocketOnclose;
    },
    websocketOnopen: function () {
      this.count = 0
      console.log("WebSocket连接成功");
    },
    websocketOnerror: function (e) {
      console.log("WebSocket连接发生错误");
      this.reconnect();
    },
    websocketOnmessage(info) {
      if (info && info.data) {
        var data = JSON.parse(info.data).data
        this.websocketMessage = data
      }
    },
    websocketOnclose: function (e) {
      this.reconnect();
    },
    reconnect() {
      this.count += 1
      if (this.count > 300) {
        this.websock.close()
        return
      }
      var that = this;
      if (that.lockReconnect) return;
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info("尝试重连...");
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    },
  }
}